<template>
    <div>
        <div ref="geoEcharts" class="geo-echart"></div>
    </div>
</template>
<script>
import * as echarts from 'echarts'
import axios from 'axios'
export default {
    name: "Geo",
    props: {
        highlightProvince: { //父组件传入高亮部分名称
            type: String,
            required: true
        },
        map_name: {//父组件传入地图名称
            type: String,
            required: true
        }
    },
    data() {
        return {
            China_map: null,
            China_option: null,
        }
    },
    mounted() {
        if (this.highlightProvince != null)
            this.initGeoEcharts();
    },
    beforeDestroy() {
        this.disposeECharts();
    },
    watch: {//实时监测高亮部分名称，一旦有变化就重新渲染地图
        highlightProvince(newhighlightProvince, oldhighlightProvince) {
            if (newhighlightProvince != null)
                this.initGeoEcharts(); // 调用子组件的方法
        }
    },
    methods: {
        initGeoEcharts() {
            axios.get('/province/' + this.map_name + '.json').then(res => {
                echarts.registerMap(this.map_name, res.data)
                this.$nextTick(() => {
                    if (this.China_map == null) this.China_map = echarts.init(this.$refs['geoEcharts'], null, { renderer: 'svg' })
                    this.China_option = {
                        tooltip: {
                            trigger: 'item',
                            formatter: function (params) {
                                return `${params.name}: ${params.value || 0}`
                            }
                        },
                        geo: {
                            map: this.map_name,
                            zoom: 1,
                            silent: true,//禁止鼠标点击
                            roam: false, // 禁止拖拽和缩放
                            selectedMode: 'none', // 选择高亮显示
                            itemStyle: {
                                areaColor: 'rgba(255,255,255,0.5)',
                                borderColor: '#02c0ff'
                            },
                        },
                    };
                    this.China_map.setOption(this.China_option);
                    if (this.highlightProvince != null && this.highlightProvince != "") {
                        this.China_map.dispatchAction({
                            type: 'geoSelect',
                            geoIndex: 0,
                            // geo 组件中 region 名称。
                            // 可以是一个数组指定多个名称。
                            name: this.highlightProvince,
                        });
                    }

                });
            });
        },
        disposeECharts() {
            if (this.China_map) {
                // 销毁 ECharts 实例
                this.China_map.dispose();
            }
        },
    },
}
</script>
<style>
.geo-echart {
    height: 400px;
    width: 400px;
}
</style>
  
  